import { asyncRoutes, constantRoutes } from '@/router'
import axios from 'axios';
import Layout from '@/layout'
import { getcurrUserMenus } from '@/api/menu';
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {    
     return loadRemoteData({ commit }, roles);
  }
}

function loadRemoteData({ commit }, roles) {
  return new Promise((resolve, reject) => {
    getcurrUserMenus()
      .then(response => {
        let accessedRoutes;
        const routes = response.data;
        const asyncRoutes = convertToAsyncRoutes(routes);
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || [];
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        }
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes); // 将结果传递给 resolve
      })
      .catch(error => {
        console.log(error);
        reject(error); // 将错误传递给 reject
      });
  });
}
 

function loadLocalhostData({ commit }, roles)
{
  return new Promise(resolve => {
    axios.get('/json/drouter.json')
      .then(response => {
        let accessedRoutes;
        const routes = response.data;
        const asyncRoutes = convertToAsyncRoutes1(routes);    
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || [];
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
        }
        commit('SET_ROUTES', accessedRoutes);
        resolve(accessedRoutes);
      })
      .catch(error => {
        console.error('Failed to load dynamic routes:', error);
        resolve([]);
      });
  });
}

function convertToAsyncRoutes1(routes) {
  console.log(routes);
  return routes.map(route => {
    const newRoute = { ...route };
    // Convert component string to actual component object
    if (newRoute.component === 'Layout') {
      newRoute.component = Layout;
    } else {
      newRoute.component = require('@/views/' + newRoute.component + '.vue').default;
    }

    // Recurse on any children
    if (newRoute.children) {
      newRoute.children = convertToAsyncRoutes1(newRoute.children);
    }

    return newRoute;
  });
}

function convertToAsyncRoutes(routes) {
  return routes
  .filter(route => route.menuType !== 2) // 过滤掉 menuType 为 2 的数据,因为是按钮
  .map(route => {
    const newRoute = {
      path: route.routerPath,
      name: route.routerName,
      component: route.routerComponent === 'LAYOUT' ? Layout : require('@/views/' + route.routerComponent + '.vue').default, // asyncLoadComponent(route.routerComponent),
      children: [],
      meta:{
        title: route.meta.title, // 将 title 添加到 meta 中
        icon: route.meta.icon, // 将 icon 添加到 meta 中
      }
    };
    // 处理子路由
    if (route.children && route.children.length > 0) {
      newRoute.children = convertToAsyncRoutes(route.children);
    }
    return newRoute;
  });
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
